/*******************************************************************************
 * Copyright (c) 2011 Erik Byström.
 * 
 * This program is free software: you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program. If
 * not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package tazadum.engine.math;

/**
 * @author Erik Byström
 * 
 */
public class Vector {
	public static Vector X = new Vector(1, 0, 0);
	public static Vector Y = new Vector(0, 1, 0);
	public static Vector Z = new Vector(0, 0, 1);

	public float x;
	public float y;
	public float z;

	public static Vector at(final float x, final float y, final float z) {
		return new Vector(x, y, z);
	}

	public Vector() {
		x = y = z = 0;
	}

	public Vector(final float x, final float y, final float z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	public Vector(final Vector p) {
		x = p.x;
		y = p.y;
		z = p.z;
	}

	public void set(final float x, final float y, final float z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	/**
	 * Normalizes the vector and returns itself.
	 * 
	 * @return
	 */
	public Vector normalize() {
		final float length = length();
		if (Float.isNaN(length)) {
			x = y = z = 0;
		}
		final float ilen = 1.0f / length;
		x *= ilen;
		y *= ilen;
		z *= ilen;
		return this;
	}

	/**
	 * Returns the length of the vector.
	 * 
	 * @return
	 */
	public float length() {
		return (float) Math.sqrt(lengthSquared());
	}

	/**
	 * Returns the square length of the vector.
	 * 
	 * @return
	 */
	public float lengthSquared() {
		return x * x + y * y + z * z;
	}

	public float[] copyTo(float[] buffer) {
		if (buffer == null) {
			buffer = new float[3];
		}
		buffer[0] = x;
		buffer[1] = y;
		buffer[2] = z;

		return buffer;
	}

	@Override
	public String toString() {
		return String.format("(%f, %f, %f)", x, y, z);
	}
}
